# -*- coding:utf-8 -*-
import serial
import sqlite3
import os




def dict_factory(cursor, row):  
    d = {}  
    for idx, col in enumerate(cursor.description):  
        d[col[0]] = row[idx]  
    return d  
    
def db_write(name,db):
    addr="./data/"+name+".db"
    if  os.path.exists('./data')==False:
        os.makedirs('./data')
        conn=sqlite3.connect(addr)
        conn.execute("create table if not exists find_db(id integer primary key autoincrement,time DATETIME DEFAULT (datetime('now', 'localtime')),name varchar(128), syslog varchar(128), addr varchar(32), info varchar(128),usr varchar(32))") 
    conn=sqlite3.connect(addr)  
    conn.isolation_level = None 
    curs=conn.cursor()
    curs.execute("insert into find_db(name,syslog,info,addr,usr)values (?,?,?,?,?)",(db['name'],db['syslog'],db['info'].decode('utf8'),db['addr'],"admin"))
    conn.commit()
    conn.close()  
    
def db_find(addr,begin_time,end_time,key_name):
    addr="./data/"+addr+".db"
    if  os.path.exists('./data')==False:
        db['flag']=u'没有任何数据，检查数据库是否损坏！！！'
        return db
    conn = sqlite3.connect(addr)  
    cur = conn.cursor() 
    # 指定工厂方法  
    conn.row_factory = dict_factory  
    cur = conn.cursor()  
    # 查询数据库
    key_name='%'+key_name+'%'
    print key_name
    cur.execute("SELECT * FROM find_db WHERE name  LIKE ? AND time >=(?) AND time <=(?);", (key_name,begin_time,end_time))  
    rows = cur.fetchall()  
    return rows




    
